﻿using UnityEngine;
using System.Collections;

public class Dialog : MonoBehaviour {

	public float time;
	public TextMesh textMesh;
	public string textEnter;
	public int maxRows;
	private string currentLineText;
	private string finalText;

	private char[] textInChar;
	private int count;

	public bool gotomenu;

	public AudioSource effect;
	private float last;

	void Start()
	{
		last = time;
		InsertText(textEnter);
	}

	void Update()
	{
		if(Input.GetMouseButton(0))
		{
			time = 0.003f;
		}
		if(Input.GetMouseButtonUp(0))
		{
			time = last;

		}
	}
	void InsertText (string text) 
	{
		count = 0;
		textInChar = new char[0];
		finalText = "";
		currentLineText = "";

		string[] textSplit = text.Split(' ');
		bool breakLineInsert = false;

		foreach (string t in textSplit) 
		{
			string tempStringCount = currentLineText + t;

			if(tempStringCount.Length >= maxRows)
			{
				currentLineText += "\n";
				finalText += currentLineText;
				currentLineText = "";
				currentLineText += t+" ";
				breakLineInsert = true;
			}
			else
			{
				currentLineText += t+" ";
				breakLineInsert = false;
			}
		}

		if(!breakLineInsert)
			finalText += currentLineText;

		textInChar = finalText.ToCharArray();
		StartCoroutine(makeFinalText());

	}

	IEnumerator makeFinalText()
	{
		yield return new WaitForSeconds(time);

		if(count < textInChar.Length)
		{
			textMesh.text += textInChar[count];
			count ++;
			StartCoroutine(makeFinalText());
			if(!effect.isPlaying)
				effect.Play();
		}
		else
		{
			FinishReadText();
		}
	}

	void FinishReadText()
	{
		StartCoroutine("finish");
	}

	IEnumerator finish()
	{
		yield return new WaitForSeconds(4);

		gameObject.AddComponent("AudioFadeManager");
		gameObject.AddComponent("ChangeScene");

		AudioSource ad = GetComponent<AudioSource>();

		GetComponent<AudioFadeManager>().FadeOut(ref ad);

		if(GetComponent<ChangeScene>().existFade())
			GetComponent<ChangeScene>().createFade("MainMenu",.5f);

	}
}
